package com.jianying.day05;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;

/**
 * ClassName: Flink01_Sink_Kafka
 * Package: com.atguigu.day05
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/3 09:04
 * @Version: 1.0
 */
public class Flink01_Sink_Kafka {
    public static void main(String[] args) throws Exception {
        // TODO 流中数据写到kafka不同主题
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);

        // TODO 流中数据类型转换
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());

        KafkaSink<WaterSensor> kfSink = KafkaSink.<WaterSensor>builder()
                .setBootstrapServers("localhost:9092,localhost:9093,localhost:9094")
                .setRecordSerializer(
                        new KafkaRecordSerializationSchema<WaterSensor>() {
                            @Nullable
                            @Override
                            public ProducerRecord<byte[], byte[]> serialize(WaterSensor waterSensor, KafkaSinkContext kafkaSinkContext, Long aLong) {
                                return new ProducerRecord<byte[], byte[]>(waterSensor.getId(),waterSensor.toString().getBytes());
                            }
                        }
                )
                .build();

        wsDS.sinkTo(kfSink);

        env.execute();

    }
}
